//
//  FlutterNativeLivePlayPlugin.m
//  Runner
//
//  Created by 小二同學 on 2020/3/13.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "FlutterNativeLivePlayPlugin.h"
#import "LivePlayViewController.h"

@interface FlutterNativeLivePlayPlugin()<LivePlayViewDelgate>

@property (nonatomic, strong) UIViewController *controller;
@property (strong,nonatomic) AFHTTPSessionManager *mgr;
@property(nonatomic, copy) FlutterResult result;
@end

@implementation FlutterNativeLivePlayPlugin
static NSString *const CHANNELNAME = @"com.ahj/livePlayPlugin";
static NSString *const METHODNAME  = @"livePlay";

/**
 *plugin 注册
 */
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:CHANNELNAME binaryMessenger:[registrar messenger]];
    
    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    FlutterNativeLivePlayPlugin *plugin = [[FlutterNativeLivePlayPlugin alloc]initWithViewController:viewController];
    
    [registrar addMethodCallDelegate:plugin channel:channel];
}

/**
 *flutter端通过通道调用原生方法时会进入以下回调
 */
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    
    if ([call.method isEqualToString:METHODNAME]) {
        self.result = result;
        NSDictionary *dic = call.arguments;
        [self kPresentPlayer:dic];
    } else {
        result(FlutterMethodNotImplemented);
    }
}

/**
 *跳转视频播放
 */
- (void)kPresentPlayer:(NSDictionary *)dic {
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setValue:dic[@"userToken"] forKey:@"TOKEN"];

    AFHTTPSessionManager *manager = [self getManager];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",dic[@"userToken"]] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",dic[@"userToken"]] forHTTPHeaderField:@"Access-Token"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:dic[@"zhiboID"] forKey:@"liveId"];
    [params setValue:dic[@"userToken"] forKey:@"token"];
    
    NSLog(@"+++++++++%@",API_URL);

    //https://jyapi.ahjtest.top/   https://jiaoyu.xinanyun.cn
    [manager POST:[NSString stringWithFormat:@"%@v1/live/detail",API_URL] parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
//        NSDictionary *dic1 = (NSDictionary *)jsonData;
        
        NSDictionary *dic2 = [[NSDictionary alloc] init];
        if ([dic1[@"data"] isKindOfClass:[NSDictionary class]]) {
            dic2 = dic1[@"data"];
        }else {
            dic2 = @{};
        }
        
        LivePlayViewController *vc = [[LivePlayViewController alloc] init];
        vc.modalPresentationStyle = 0;
        [vc preparePlayWithInfo:dic2];
        vc.delegate = self;
        [self.controller presentViewController:vc animated:YES completion:nil];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 返回按钮
- (void)BackButtonDelegate:(UIButton *)backButton {
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    self.result(@"FRESHDATA");
}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.controller = viewController;
    }
    return self;
}

- (AFHTTPSessionManager *)getManager
{
    _mgr = [AFHTTPSessionManager manager];
    [_mgr.requestSerializer setTimeoutInterval:10];
    _mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    _mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    _mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    _mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    return _mgr;
}
@end
